
package biblio.service.book;


import biblio.bean.BookBean;
import biblio.dao.BookDAO;
import biblio.dao.CategoryDAO;
import biblio.domain.Book;
import biblio.domain.Category;
import biblio.exception.NoSuchEntityException;
import biblio.util.SourceName;
import biblio.util.interfaces.RequestOperationHelper;
import java.util.List;
import java.util.logging.Level;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;


/**
 *
 * @author mephisto
 */
@ManagedBean(name="bookService")
@ApplicationScoped
public class BookServiceImpl implements BookService
{
    public void create()
    {
        RequestOperationHelper rOH = (RequestOperationHelper)appContext.getBean("rOH");
        bookBean = (BookBean) rOH.getBean("bookBean");
        Book book = new Book();
        book.setId(bookBean.getId());
        book.setTitle(bookBean.getTitle());
        book.setISBN(bookBean.getISBN());
        book.setPagesNumber(bookBean.getPagesNumber());
        book.setPublishingDate(bookBean.getPublishingDate());
        CategoryDAO categoryDAO = (CategoryDAO)appContext.getBean("catDAO");
        BookDAO bookDAO = (BookDAO)appContext.getBean("bookDAO");
        try
        {
            book.setCategory(categoryDAO.find(bookBean.getCategoryName())); 
        }
        catch (NoSuchEntityException ex)
        {
            log.error(ex.getMessage());
        }
        bookDAO.create(book);
        bookBean.clear();
    }

    public void update(Book book)
    {
        log.debug("Book for update: " + book.getId());

        BookDAO bookDAO = (BookDAO)appContext.getBean("bookDAO");
        try
        {
            bookDAO.update(book);
        }
        catch (NoSuchEntityException ex)
        {
            log.error("Entity with id: " + book.getId() + "does not exist in the database");
            log.error(ex.getMessage());
        }
    }

    public void delete(Book book)
    {
        BookDAO bookDAO = (BookDAO)appContext.getBean("bookDAO");
        try
        {
            bookDAO.delete(book);
        }
        catch(DataAccessException e)
        {
            log.error("Entity with id: " + book.getId() + "does not exist in the database");
            log.error(e);
        }
    }

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.AUX_APPLICATION_CONTEXT,
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(BookServiceImpl.class);
    private BookBean bookBean;
}
